﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace YouTubeStormer
{
    public partial class Log : UserControl
    {
        public Log()
        {
            InitializeComponent();
        }

        public class LogOject
        {
            public string Text { get; set; }
            public string LinkText { get; set; }
            public string Link { get; set; }
            public override string ToString()
            {
                return Text + Link;
            }
        }

        private void richTextBoxWithLinking_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            Process.Start(linkDictionary[e.LinkText]);
        }

        Dictionary<string, string> linkDictionary = new Dictionary<string, string>();
        public string Store = "";

        delegate void LogHelperDelegate(LogOject logObject);
        void LogHelper(LogOject logObject)
        {

            if (richTextBoxWithLinking.InvokeRequired) { richTextBoxWithLinking.Invoke(new LogHelperDelegate(LogHelper), logObject); }
            else
            {
                richTextBoxWithLinking.SelectionStart = richTextBoxWithLinking.Text.Length;
                if (logObject.Link != "")
                {
                    var textParts = Regex.Split(logObject.Text, "{LINK}");
                    richTextBoxWithLinking.SelectedText = textParts[0];
                    richTextBoxWithLinking.InsertLink(logObject.LinkText, richTextBoxWithLinking.Text.Length);
                    if (!linkDictionary.ContainsKey(logObject.LinkText)) linkDictionary.Add(logObject.LinkText, logObject.Link);
                    richTextBoxWithLinking.SelectionStart = richTextBoxWithLinking.Text.Length;
                    richTextBoxWithLinking.SelectedText = textParts[1];

                    Store += logObject.Text.Replace("{LINK}", "<a href=\"" + logObject.Link + "\">" + logObject.LinkText + "</a>") + Environment.NewLine;
                }
                else
                {
                    richTextBoxWithLinking.SelectedText = logObject.Text;
                    Store += logObject.Text + Environment.NewLine;
                }
                richTextBoxWithLinking.SelectionStart = richTextBoxWithLinking.Text.Length;
                richTextBoxWithLinking.SelectedText = Environment.NewLine;
                richTextBoxWithLinking.ScrollToCaret();

            }
        }

        public void PerformLog(string text, string link = "", string linkText = "", bool EmptyStore = false)
        {
            LogHelper(new Log.LogOject { Text = text, Link = link, LinkText = linkText });
            if (EmptyStore) Store = "";
        }
    }
}
